﻿using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.SignalR.Client;
using System.ComponentModel.DataAnnotations;
using TrackSystem.IO.Equip;
using TrackSystem.UI.Server.Features;

namespace TrackSystem.UI.Server.Pages.IOControl;

public partial class EquipControlPage : ComponentBase
{
    [Required] private HubConnection? _hubIo;

    List<EquipItem>? _equipItems;
    private Dictionary<Guid, string> _alarmMsg;
    private int _numAlarm;

    private string _message;
    private PartSelect? _selectedPart = new PartSelect();

    /// <summary>
    /// 首次渲染
    /// </summary>
    /// <param name="firstRender"></param>
    /// <returns></returns>
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            try
            {
                // 建立SIGNALR连接
                _hubIo = new HubConnectionBuilder()
                    .WithUrl("http://localhost:5000/ioctlhub")
                    .WithAutomaticReconnect(new[] { TimeSpan.Zero, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(10) })
                    .Build();

                await _hubIo.StartAsync();

                // 注册查询端口状态响应函数
                _hubIo.On<List<EquipItem>>("HandleInitAcquireEquip", (tt) =>
                {
                    _equipItems = tt;
                    _message += $" {DateTime.Now.ToLocalTime()}查询设备列表成功";
                    InvokeAsync(StateHasChanged);
                });

                _hubIo.On<Dictionary<Guid, string>, int>("HandleAcquireAlarmMessage", (tt, num) =>
                {
                    _alarmMsg = tt;
                    _numAlarm = num;
                    _message += $" {DateTime.Now.ToLocalTime()} 查询报警列表成功";
                    InvokeAsync(StateHasChanged);
                });

                _hubIo.On<PartSelect>("HandleAcquirePart", (tt) =>
                {
                    _selectedPart = tt;
                    _message += $" {DateTime.Now.ToLocalTime()} 查询部件成功";
                    InvokeAsync(StateHasChanged);
                });

                // 注册初始化传感器响应函数
                _hubIo.On<string>("HandleInitEquip", (tt) =>
                {
                    _message = $" {DateTime.Now.ToLocalTime()}" + tt;
                    InvokeAsync(StateHasChanged);
                });

                var timer = new System.Timers.Timer(1000);
                timer.Elapsed += async (s, e) =>
                {
                    try
                    {
                        _message = "";
                        await _hubIo.SendAsync("AcquireEquip");
                        await _hubIo.SendAsync("AcquirePartByName", _selectedPart?.CurrentName);
                        await _hubIo.SendAsync("AcquireAlarmMessage");
                    }
                    catch (Exception ex)
                    {
                        _message = ex.Message;
                        await InvokeAsync(StateHasChanged);
                    }
                };
                timer.Start();

                _message = "SignalR连接成功";
            }
            catch (Exception ex)
            {
                _message = ex.Message;
            }

            StateHasChanged();
        }
    }


    private async Task BtnInitEquips()
    {
        try
        {
            if (_hubIo != null && _hubIo.State == HubConnectionState.Connected)
                await _hubIo.SendAsync("InitialEquip");
        }
        catch (Exception ex)
        {
            _message = ex.Message;
            await InvokeAsync(StateHasChanged);
        }
    }

    private async Task BtnUnloadEquips()
    {
        try
        {
            if (_hubIo != null && _hubIo.State == HubConnectionState.Connected)
                await _hubIo.SendAsync("UnloadEquip");
        }
        catch (Exception ex)
        {
            _message = ex.Message;
            await InvokeAsync(StateHasChanged);
        }
    }

    /// <summary>
    /// 初始化传感器
    /// </summary>
    /// <returns></returns>
    private async Task BtnInitAll()
    {
        try
        {
            if (_hubIo != null && _hubIo.State == HubConnectionState.Connected)
            {
                await _hubIo.SendAsync("InitialEquip");
                await _hubIo.SendAsync("InitialRegs");
                await _hubIo.SendAsync("InitialSensors");
                await _hubIo.SendAsync("InitLogics");
                await _hubIo.SendAsync("InitLoops");
            }
        }
        catch (Exception ex)
        {
            _message = ex.Message;
            await InvokeAsync(StateHasChanged);
        }
    }

    /// <summary>
    /// 初始化传感器
    /// </summary>
    /// <returns></returns>
    private async Task BtnUninitAll()
    {
        try
        {
            if (_hubIo != null && _hubIo.State == HubConnectionState.Connected)
            {
                await _hubIo.SendAsync("UnloadEquip");
                await _hubIo.SendAsync("UnloadSensors");
                await _hubIo.SendAsync("UnloadRegs");
                await _hubIo.SendAsync("UnloadLogics");
                await _hubIo.SendAsync("UnloadLoops");
            }
        }
        catch (Exception ex)
        {
            _message = ex.Message;
            await InvokeAsync(StateHasChanged);
        }
    }


    private Task BtnBack()
    {
        if (_selectedPart != null)
            _selectedPart.CurrentName = "";
        return Task.CompletedTask;
    }
}

